﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    debioscoopEntities db;
    String redirect;

    protected void Page_Load(object sender, EventArgs e)
    {
        db = (debioscoopEntities)Session["db"];
        redirect = "default.aspx";

        if (!String.IsNullOrEmpty(Request.QueryString["logout"]))
        {
            if (Request.QueryString["logout"].Equals("true"))
            {
                Session["user"] = null;
            }
        }

        if (!String.IsNullOrEmpty(Request.QueryString["redirect"]))
        {
            redirect = Request.QueryString["redirect"];
        }

        if (Master.getUser() != null)
        {
            takeMeAway();
        }

        if (!IsPostBack)
        {
            if (!String.IsNullOrEmpty(Request.QueryString["username"]))
            {
                txtUsername.Text = Request.QueryString["username"];
                lblMessage.Text = Master.tl.getTranslation("accountActivated");
            }

            ddlSex.Items.Add(new ListItem(Master.tl.getTranslation("male"), "m"));
            ddlSex.Items.Add(new ListItem(Master.tl.getTranslation("female"), "v"));

            ddlLanguage.Items.Add(new ListItem(Master.tl.getTranslation("dutch"), "NL"));
            ddlLanguage.Items.Add(new ListItem(Master.tl.getTranslation("english"), "EN"));

        }

        lblFirstname.Text           = Master.tl.getTranslation("firstname");
        lblInsertion.Text           = Master.tl.getTranslation("insertion");
        lblLastname.Text            = Master.tl.getTranslation("lastname");
        lblRegUsername.Text         = Master.tl.getTranslation("username");
        lblRegPassword.Text         = Master.tl.getTranslation("password");
        lblRegPasswordConfirm.Text  = Master.tl.getTranslation("passwordConfirm");
        lblEmail.Text               = Master.tl.getTranslation("email");
        lblBirthdate.Text           = Master.tl.getTranslation("birthdate");
        lblStreetname.Text          = Master.tl.getTranslation("streetname");
        lblHouseNumber.Text         = Master.tl.getTranslation("houseNumber");
        lblZip.Text                 = Master.tl.getTranslation("zip");
        lblSex.Text                 = Master.tl.getTranslation("sex");
        lblLanguage.Text            = Master.tl.getTranslation("selectLanguage");
        cbNewsletter.Text           = Master.tl.getTranslation("receiveNewsletter");
        lblUsername.Text            = Master.tl.getTranslation("username");
        lblPassword.Text            = Master.tl.getTranslation("password");
        lblRegister.Text            = Master.tl.getTranslation("register");
        lblLogin.Text               = Master.tl.getTranslation("login");
        btnLogin.Text               = Master.tl.getTranslation("login");
        btnRegister.Text            = Master.tl.getTranslation("register");
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        String username = txtUsername.Text;
        String password = txtPassword.Text;

        List<account> users = new List<account>();

        if( !username.Equals("") && !password.Equals(""))
        {
            users = db.accounts.Where(a => a.gebruikersnaam.Equals(username)).ToList();

            if (users.Count > 0)
            {
                //hash password
                PasswordManager pm = new PasswordManager();
                password = pm.EncodePassword(password);

                users = db.accounts.Where(a => a.gebruikersnaam.Equals(username) && a.wachtwoord.Equals(password) && a.actief == true).ToList();

                if (users.Count > 0)
                {
                    Session["user"] = users[0];

                    takeMeAway();
                }
                else
                {
                    showMessage( Master.tl.getTranslation("wrongPassword") );
                }
   
            }
            else
            {
                showMessage( Master.tl.getTranslation("username") + ": " + username + " " + Master.tl.getTranslation("notFound") );
            }
        }
    }

    protected void btnRegister_Click(object sender, EventArgs e)
    {
        String firstname = (!txtFirstname.Text.Equals("")) ? txtFirstname.Text : null;
        String insertion = (!txtInsertion.Text.Equals("")) ? txtInsertion.Text : null;
        String lastname = (!txtLastname.Text.Equals("")) ? txtLastname.Text : null;
        String username = (!txtRegUsername.Text.Equals("")) ? txtRegUsername.Text : null;
        String password = (!txtRegPassword.Text.Equals("")) ? txtRegPassword.Text : null;
        String passwordConfirm = (!txtRegPasswordConfirm.Text.Equals("")) ? txtRegPasswordConfirm.Text : null;
        String email = (!txtEmail.Text.Equals("")) ? txtEmail.Text : null;
        String streetName = (!txtStreetname.Text.Equals("")) ? txtStreetname.Text : null;
        int houseNumber = (!txtHouseNumber.Text.Equals("")) ? int.Parse(txtHouseNumber.Text) : 0;
        String zipCode = (!txtZip.Text.Equals("")) ? txtZip.Text : null;
        String sex = ddlSex.SelectedItem.Value;
        String language = ddlLanguage.SelectedItem.Value;
        bool newsletter = cbNewsletter.Checked;
        List<account> accounts = new List<account>();
        DateTime birthdate = DateTime.Now;

        if (!txtBirthdate.Equals("") && !txtBirthdate.Equals("dd-mm-jjjj"))
        {
            int year = 0;
            int month = 0;
            int day = 0;

            String wholeDate = txtBirthdate.Text;
            String[] splittedBirthDate = wholeDate.Split('-').ToArray();

            if (splittedBirthDate.Length > 1)
            {
                //Dutch date
                if (splittedBirthDate[0].Length == 4)
                {
                    year = int.Parse(splittedBirthDate[0]);
                    month = int.Parse(splittedBirthDate[1]);
                    day = int.Parse(splittedBirthDate[2]);
                }
                //English date
                else if (splittedBirthDate[2].Length == 4)
                {
                    year = int.Parse(splittedBirthDate[2]);
                    month = int.Parse(splittedBirthDate[1]);
                    day = int.Parse(splittedBirthDate[0]);
                }

                birthdate = new DateTime(year, month, day);
            }
        }

        List<String> messages = new List<String>();
        //hash MD5 password
        PasswordManager pm = new PasswordManager();
        password = pm.EncodePassword(password);
        passwordConfirm = pm.EncodePassword(passwordConfirm);
        EmailManager em = new EmailManager();

        //CHECK ALL THE FIELDS !
        if (firstname != null && lastname != null && username != null &&
            password != null && passwordConfirm != null && email != null &&
            birthdate < DateTime.Now)
        {
            //All the fields that are required are filled in (:
            //We have to check if the username is already taken
            accounts = db.accounts.Where(a => a.gebruikersnaam.Equals(username)).ToList();
            if (accounts.Count < 1)
            {
                //Okay the username is free, now check if the passwords are the same
                if (password.Equals(passwordConfirm))
                {
                    try
                    {
                        //We are ready to go and add the account in the database
                        account newAccount = new account();
                        newAccount.voornaam = firstname;
                        newAccount.tussenvoegsel = (insertion != null) ? insertion : "";
                        newAccount.achternaam = lastname;
                        newAccount.gebruikersnaam = username;
                        newAccount.wachtwoord = password;
                        newAccount.email = email;
                        newAccount.geboortedatum = birthdate;
                        newAccount.straat = (streetName != null) ? streetName : "";
                        newAccount.huisnummer = (streetName != null && houseNumber > 0) ? houseNumber.ToString() : "";
                        newAccount.postcode = (zipCode != null) ? zipCode : "";
                        newAccount.geslacht = sex;
                        newAccount.taal = language;
                        newAccount.nieuwsbrief = newsletter;

                        db.accounts.Add(newAccount);
                        db.SaveChanges();

                        String ip = Request.ServerVariables["REMOTE_ADDR"];

                        ListDictionary parameters = new ListDictionary();
                        parameters.Add("<%username%>", username);
                        parameters.Add("<%firstname%>", firstname);
                        parameters.Add("<%lastname%>", lastname);
                        parameters.Add("<%url%>", "http://localhost:" + Request.Url.Port + "/debioscoop/Account.aspx?username=" + username + "&code=" + pm.EncodePassword(ip + username + ip));
                        String subject = Master.tl.getTranslation("accountActivation");
                        String body = Master.tl.getTranslation("mailDear") + " <%firstname%> <%lastname%>,<br />";
                        body += "<br />";
                        body += Master.tl.getTranslation("madeAccount") + ", <a href='http://localhost:" + Request.Url.Port + "/debioscoop/Default.aspx'>http://www.debioscoop.nl</a>.<br />";
                        body += Master.tl.getTranslation("beforeLogin") + ".<br />";
                        body += Master.tl.getTranslation("clickLink") + " <a href='<%url%>'>" + Master.tl.getTranslation("clickLinkText") + "</a>";

                        em.sendEmail(email, subject, parameters, body);

                        lblMessage.Text = Master.tl.getTranslation("activationLinkSend");

                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                    {
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                            }
                        }
                    }

                }
            }
        }

        if (firstname == null) { messages.Add(Master.tl.getTranslation("errorFirstname")); }
        if (lastname == null) { messages.Add(Master.tl.getTranslation("errorLastName")); }
        if (username == null) { messages.Add(Master.tl.getTranslation("errorUsername")); }
        if (password == null) { messages.Add(Master.tl.getTranslation("errorPassword")); }
        if (passwordConfirm == null) { messages.Add(Master.tl.getTranslation("errorPassword2")); }
        if (email == null) { messages.Add(Master.tl.getTranslation("errorEmail")); }
        if (birthdate == DateTime.Now) { messages.Add(Master.tl.getTranslation("errorBirthdate")); }
        if (password != null && passwordConfirm != null && !password.Equals(passwordConfirm)) { messages.Add(Master.tl.getTranslation("errorPassword3")); }
        if (accounts.Count >= 1) { messages.Add(Master.tl.getTranslation("username") + ": " + username + " " + Master.tl.getTranslation("alreadyExists")); }

        lblMessage.Text = "";

        foreach (String message in messages)
        {
            lblMessage.Text += message + "<br />";
        }

        if (messages.Count > 0)
        {
            lblMessage.CssClass += " show";
        }
    }

    private void showMessage(String message)
    {
        lblMessage.CssClass += " show";
        lblMessage.Text = message;
    }

    private void takeMeAway()
    {
       Response.Redirect("~/" + redirect);
    }
}